package top.stmo.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.stmo.pojo.Books;
import top.stmo.service.BooksService;
import top.stmo.vo.Code;
import top.stmo.vo.Result;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BooksController {

    @Autowired
    private BooksService booksService;

    @PostMapping
    public Result save(@RequestBody Books books) {
        boolean flag = booksService.save(books);
        return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR,flag);
    }

    @PutMapping
    public Result update(@RequestBody Books books) {
        boolean flag = booksService.update(books);
        return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR,flag);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean flag = booksService.delete(id);
        return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERR,flag);
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
//        int a = 1/0;
        Books books = booksService.getById(id);
        Integer code = books != null ? Code.GET_OK : Code.GET_ERR;
        String msg = books != null ? "" : "数据查询失败";
        return new Result(code,books,msg);
    }

    @GetMapping
    public Result getAll() {
        List<Books> booksList = booksService.getAll();
        Integer code = booksList != null ? Code.GET_OK : Code.GET_ERR;
        String msg = booksList != null ? "" : "数据查询失败";
        return new Result(code,booksList,msg);
    }

}
